import type { Player, PlayerCategory } from "@/lib/types"
import { Trophy, ChevronUp, Users, Search, Shield, ArrowUp, Star } from "lucide-react"
import { useState, useEffect } from "react"
import PlayerModal from "./player-modal"
import ModeIcon from "./mode-icons"
import { getTitleByScore } from "@/lib/utils"

interface TierViewProps {
  players: Player[]
  category: PlayerCategory
}

// API中使用的数值段位到名称的映射
const TIER_NAMES: Record<number, string> = {
  1: 'HT1',
  2: 'LT1',
  3: 'HT2',
  4: 'LT2',
  5: 'HT3',
  6: 'LT3',
  7: 'HT4',
  8: 'LT4',
  9: 'HT5',
  10: 'LT5'
};

// 将类别映射到tier数值属性
const categoryToTierProp: Record<string, string> = {
  "combat": "swordTier",
  "crystal": "crystalTier",
  "heart": "buhcTier",
  "potion": "potionTier", 
  "discord": "npotTier",
  "circle": "smpTier"
};

// 将类别映射到tier名称属性
const categoryToTierNameProp: Record<string, string> = {
  "combat": "swordTierName",
  "crystal": "crystalTierName",
  "heart": "buhcTierName",
  "potion": "potionTierName", 
  "discord": "npotTierName",
  "circle": "smpTierName"
};

export default function TierView({ players, category }: TierViewProps) {
  const [selectedPlayer, setSelectedPlayer] = useState<Player | null>(null);
  const [searchQuery, setSearchQuery] = useState("");
  const [filteredPlayers, setFilteredPlayers] = useState<Record<string, Player[]>>({});
  const [tierCounts, setTierCounts] = useState<Record<string, number>>({});
  const [showScrollTop, setShowScrollTop] = useState(false);
  
  useEffect(() => {
    // 在组件加载时为分组添加动画延迟
    const timer = setTimeout(() => {
      // 这个空的定时器仅用于触发动画
    }, 100);
    return () => clearTimeout(timer);
  }, []);
  
  // 检测滚动位置以显示/隐藏回到顶部按钮
  useEffect(() => {
    const handleScroll = () => {
      setShowScrollTop(window.scrollY > 300);
    };
    
    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  }, []);
  
  // 回到顶部功能
  const scrollToTop = () => {
    window.scrollTo({
      top: 0,
      behavior: 'smooth'
    });
  };
  
  // 处理选择玩家事件
  const handleSelectPlayer = (player: Player) => {
    // 获取当前分数
    const currentPoints = player.overallScore || player.title?.points || 0;
    
    // 根据总分获取称号
    const titleInfo = getTitleByScore(currentPoints);
    
    // 创建一个新的玩家对象，更新称号信息
    const updatedPlayer = {
      ...player,
      title: {
        name: titleInfo.name,
        color: titleInfo.color,
        points: currentPoints,
        icon: titleInfo.icon,
        description: titleInfo.description
      }
    };
    
    // 设置为选中的玩家
    setSelectedPlayer(updatedPlayer);
  };
  
  // 搜索过滤功能
  useEffect(() => {
    if (!searchQuery) {
      // 重置为原始分组
      const groups: Record<string, Player[]> = {};
      let counts: Record<string, number> = {};
      
      // 初始化空数组
      for (let i = 1; i <= 5; i++) {
        groups[`Tier ${i}`] = [];
        counts[`Tier ${i}`] = 0;
      }
      
      // 重新分配玩家
      players.forEach(player => {
        const tierValue = player.tier !== undefined && player.tier !== null 
          ? Number(player.tier) 
          : null;
          
        if (tierValue !== null) {
          let tierLevel = "";
          
          if (tierValue <= 2) {
            tierLevel = "Tier 1";
          } else if (tierValue <= 4) {
            tierLevel = "Tier 2";
          } else if (tierValue <= 6) {
            tierLevel = "Tier 3";
          } else if (tierValue <= 8) {
            tierLevel = "Tier 4";
          } else if (tierValue <= 10) {
            tierLevel = "Tier 5";
          }
          
          if (tierLevel && groups[tierLevel]) {
            groups[tierLevel].push(player);
            counts[tierLevel]++;
          }
        }
      });
      
      setFilteredPlayers(groups);
      setTierCounts(counts);
    } else {
      // 根据搜索词过滤
      const query = searchQuery.toLowerCase();
      const groups: Record<string, Player[]> = {};
      let counts: Record<string, number> = {};
      
      // 初始化空数组
      for (let i = 1; i <= 5; i++) {
        groups[`Tier ${i}`] = [];
        counts[`Tier ${i}`] = 0;
      }
      
      // 重新分配符合搜索条件的玩家
      players.forEach(player => {
        const nameMatch = player.name.toLowerCase().includes(query);
        const regionMatch = player.region && player.region.toLowerCase().includes(query);
        const titleMatch = player.title && player.title.name.toLowerCase().includes(query);
        
        if (nameMatch || regionMatch || titleMatch) {
          const tierValue = player.tier !== undefined && player.tier !== null 
            ? Number(player.tier) 
            : null;
            
          if (tierValue !== null) {
            let tierLevel = "";
            
            if (tierValue <= 2) {
              tierLevel = "Tier 1";
            } else if (tierValue <= 4) {
              tierLevel = "Tier 2";
            } else if (tierValue <= 6) {
              tierLevel = "Tier 3";
            } else if (tierValue <= 8) {
              tierLevel = "Tier 4";
            } else if (tierValue <= 10) {
              tierLevel = "Tier 5";
            }
            
            if (tierLevel && groups[tierLevel]) {
              groups[tierLevel].push(player);
              counts[tierLevel]++;
            }
          }
        }
      });
      
      setFilteredPlayers(groups);
      setTierCounts(counts);
    }
  }, [searchQuery, players]);
  
  // 段位顺序（从高到低）
  const tiers = ["Tier 1", "Tier 2", "Tier 3", "Tier 4", "Tier 5"];
  
  // 计算总玩家数
  const totalPlayers = tiers.reduce((sum, tier) => sum + (tierCounts[tier] || 0), 0);

  return (
    <div className="space-y-4 relative">
      {/* 页面顶部装饰元素 */}
      <div className="absolute top-0 right-0 w-48 h-48 bg-blue-500/5 rounded-full blur-3xl -z-10 transform translate-x-1/3 -translate-y-1/3"></div>
      <div className="absolute top-1/3 left-0 w-32 h-32 bg-purple-500/5 rounded-full blur-2xl -z-10 transform -translate-x-1/3"></div>
      <div className="absolute bottom-0 right-1/4 w-40 h-40 bg-yellow-500/5 rounded-full blur-3xl -z-10"></div>
      
      {/* 回到顶部按钮 */}
      {showScrollTop && (
        <button 
          onClick={scrollToTop}
          className="scroll-top-btn"
          aria-label="回到顶部"
        >
          <ArrowUp className="h-5 w-5" />
        </button>
      )}
      
      {/* 搜索和统计信息 */}
      <div className="glass-card rounded-lg p-4 shadow-md">
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
          {/* 搜索框 */}
          <div className="relative flex-1">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
            <input 
              type="text" 
              placeholder="搜索玩家..." 
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="w-full bg-[#252932] text-gray-200 pl-9 pr-4 py-2 rounded-md focus:outline-none focus:ring-1 focus:ring-blue-500 placeholder-gray-500 transition-all duration-200 border border-gray-700/30"
            />
          </div>
          
          {/* 统计信息 */}
          <div className="flex items-center gap-3 text-sm text-gray-400 bg-[#252932] px-3 py-1.5 rounded-md border border-gray-700/30">
            <div className="flex items-center gap-1">
              <Users className="h-4 w-4 text-blue-400/80" />
              <span>共 {totalPlayers} 名玩家</span>
            </div>
            <span className="text-gray-600">|</span>
            <div className="flex items-center gap-1">
              <Shield className="h-4 w-4 text-yellow-400/80" />
              <span>{getCategoryName(category)}段位</span>
            </div>
          </div>
        </div>
      </div>
      
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-3 md:gap-4 animate-fade-in">
        {tiers.map((tier, tierIndex) => {
          const tierPlayers = filteredPlayers[tier] || [];
          const playerCount = tierCounts[tier] || 0;

          return (
            <div 
              key={tier} 
              className="bg-[#1e2126]/70 backdrop-blur-sm rounded-md overflow-hidden shadow-lg hover:shadow-xl transition-all duration-300 animate-slide-up border border-gray-800/40" 
              style={{ animationDelay: `${tierIndex * 0.1}s` }}
            >
              <div 
                className="w-full flex items-center justify-between p-3 bg-gradient-to-r from-[#252932]/90 to-[#1e2228]/90 hover:from-[#2a2f38]/90 hover:to-[#23272e]/90 transition-colors border-b border-gray-800/50"
              >
                <div className="flex items-center gap-2">
                  <Trophy className={`h-4 w-4 md:h-5 md:w-5 ${getTierTrophyColor(tier)}`} />
                  <h2 className="font-bold text-base md:text-lg">{tier}</h2>
                </div>
                <div className="flex items-center gap-2">
                  <span className="text-xs bg-[#323842] px-2 py-0.5 rounded-full text-gray-300 border border-gray-700/30">{playerCount}</span>
                </div>
              </div>

              <div className="max-h-[500px] overflow-y-auto custom-scrollbar">
                {tierPlayers.length === 0 ? (
                  <div className="p-6 text-center text-gray-400 text-sm">
                    <Star className="h-6 w-6 text-gray-600 mx-auto mb-2" />
                    暂无玩家
                  </div>
                ) : (
                  tierPlayers.map((player, playerIndex) => {
                    // 获取玩家的tier值
                    const tierValue = player.tier !== undefined && player.tier !== null 
                      ? Number(player.tier) 
                      : null;
                    // 判断是HT还是LT (奇数是HT，偶数是LT)
                    const isHighTier = tierValue !== null && tierValue % 2 === 1;
                    
                    // 根据排名生成渐变背景色
                    const getPlayerBgStyle = () => {
                      if (player.rank === 1) return { background: "linear-gradient(to right, rgba(251, 191, 36, 0.1), rgba(217, 119, 6, 0.05))" };
                      if (player.rank === 2) return { background: "linear-gradient(to right, rgba(209, 213, 219, 0.1), rgba(156, 163, 175, 0.05))" };
                      if (player.rank === 3) return { background: "linear-gradient(to right, rgba(180, 83, 9, 0.1), rgba(146, 64, 14, 0.05))" };
                      return { 
                        background: isHighTier ? "#1a1d23" : "#20242b" 
                      };
                    };
                    
                    return (
                      <div
                        key={player.id}
                        className={`flex items-center justify-between px-3 py-2 md:p-3 border-l-2 hover:brightness-110 cursor-pointer transition-all duration-200 animate-fade-in hover-scale hover:translate-x-1`}
                        style={{ 
                          animationDelay: `${(tierIndex * 0.1) + (playerIndex * 0.05)}s`,
                          borderLeftColor: isHighTier ? "#60a5fa" : "#4ade80",
                          ...getPlayerBgStyle()
                        }}
                        onClick={() => handleSelectPlayer(player)}
                      >
                        <div className="flex items-center gap-2 min-w-0">
                          <div className="relative">
                            <img 
                              src={player.avatar || "/placeholder-user.jpg"} 
                              alt={player.name}
                              className="w-6 h-6 rounded-full hidden sm:block object-cover border border-gray-700 hover:border-gray-500 transition-colors"
                              onError={(e) => {
                                e.currentTarget.src = "/placeholder-user.jpg"; 
                                e.currentTarget.onerror = null;
                              }}
                            />
                            {player.rank && player.rank <= 3 && (
                              <div className="absolute -top-1 -right-1 hidden sm:block">
                                <span className="flex h-2 w-2 rounded-full bg-yellow-500 opacity-75"></span>
                              </div>
                            )}
                          </div>
                          <div className="min-w-0">
                            <span className="truncate text-white text-sm md:text-base font-medium block">{player.name}</span>
                            {player.title && (
                              <span className="text-xs truncate block" style={{ color: player.title?.color || "#808080" }}>
                                {player.title.name}
                              </span>
                            )}
                          </div>
                        </div>
                        <div className="flex items-center gap-2">
                          <div className="text-xs bg-[#323842] px-1.5 py-0.5 rounded text-gray-300 hidden sm:block border border-gray-700/30">#{player.rank || '-'}</div>
                          <ChevronUp className="h-4 w-4 text-gray-400 flex-shrink-0 transform transition-transform hover:translate-y-[-2px]" />
                        </div>
                      </div>
                    );
                  })
                )}
              </div>
            </div>
          );
        })}
      </div>
      
      {/* 搜索无结果提示 */}
      {searchQuery && totalPlayers === 0 && (
        <div className="glass-card rounded-lg p-6 text-center my-8 animate-fade-in shadow-lg">
          <Search className="h-10 w-10 text-gray-500 mx-auto mb-2" />
          <h3 className="text-lg font-medium text-gray-300 mb-1">未找到匹配的玩家</h3>
          <p className="text-sm text-gray-500">尝试使用不同的搜索词</p>
          <button 
            onClick={() => setSearchQuery('')}
            className="mt-4 px-4 py-2 gradient-btn rounded-md text-sm"
          >
            清除搜索
          </button>
        </div>
      )}
      
      {/* 自定义滚动条样式 */}
      <style jsx global>{`
        .custom-scrollbar::-webkit-scrollbar {
          width: 6px;
        }
        .custom-scrollbar::-webkit-scrollbar-track {
          background: #1a1d23;
        }
        .custom-scrollbar::-webkit-scrollbar-thumb {
          background-color: #4a5568;
          border-radius: 6px;
        }
        .custom-scrollbar::-webkit-scrollbar-thumb:hover {
          background-color: #718096;
        }
        
        @media (max-width: 768px) {
          .custom-scrollbar::-webkit-scrollbar {
            width: 4px;
          }
        }
      `}</style>
      
      {/* 玩家详情模态窗口 */}
      {selectedPlayer && (
        <PlayerModal 
          player={selectedPlayer} 
          isOpen={!!selectedPlayer} 
          onClose={() => setSelectedPlayer(null)} 
        />
      )}
    </div>
  );
}

function getTierTrophyColor(tier: string): string {
  switch (tier) {
    case "Tier 1":
      return "text-yellow-500"
    case "Tier 2":
      return "text-gray-400"
    case "Tier 3":
      return "text-amber-600"
    case "Tier 4":
      return "text-zinc-400"
    default:
      return "text-zinc-600"
  }
}

function getCategoryName(category: string): string {
  switch(category) {
    case "overall": return "总体";
    case "combat": return "剑术";
    case "crystal": return "水晶";
    case "heart": return "UHC";
    case "potion": return "药水";
    case "discord": return "合金pot";
    case "circle": return "SMP";
    default: return category;
  }
}

